package top.carrotguo.weibo.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import top.carrotguo.weibo.view.IView;
import top.carrotguo.weibo.R;
import top.carrotguo.weibo.widget.LoadingDialog;

/**
 * Created by carrot on 2018-10-11.
 */

public abstract class BaseFragment extends Fragment implements IView {

    public final String TAG = this.getClass().getSimpleName();

    //用于懒加载，判断fragment是否已经加载了布局
    private boolean isCreated = false;

    //上下文（获取activity的上下文）
    protected AppCompatActivity mContext;

    //fragment的根布局
    protected View mRootView;

    //fragment的标题栏
    public Toolbar mToolbar;

    public TextView mTvCenterTitle;

    private LoadingDialog mLoadingDialog;
    private boolean isFirst = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        mContext = (AppCompatActivity) getActivity();

        //判断是否有传来数据
        if (null != getArguments()) {
            getBundleExtras(getArguments());
        }

        //生成根布局
        if (null != mRootView) {
            //移除父控件包含的旧布局
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (null != parent) {
                parent.removeView(mRootView);
            }
        } else {
            mRootView = initContentView(inflater,container,savedInstanceState);
        }

        mToolbar = mRootView.findViewById(R.id.toolbar);

        if (null != mToolbar) {
            initToolbar(mRootView);
        }

        //懒加载使用（判断布局是否加载完成）
        isCreated = true;

        return mRootView;
    }

    /**
     * fragment可见时调用，但是可能执行于onActivityCreate之前（当使用viewpager时它会在onActivityCreate后调用），因此控件未初始化，不能调用控件
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isCreated && isFirst) {
            isFirst = false;
            initLogic();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //activity创建完成时，需要查看fragment是否可见，若可见,并且还未加载数据，则加载数据
        if (getUserVisibleHint() && isFirst) {
            isFirst = false;
            initLogic();
        }
    }

    /**
     * 初始化标题居中的标题
     * @param view
     */
    protected void initToolbar(View view){
        mTvCenterTitle = view.findViewById(R.id.tv_center_title);
    }

    public void setCenterTitle(String title){
        if (mTvCenterTitle != null) {
            mTvCenterTitle.setText(title);
        }
    }

    public void setTitle(String title){
        if (mToolbar != null) {
            mToolbar.setTitle(title);
        }
    }

    public void showLoading(){
//        mLoadingDialog =
//                new LoadingDialog.Builder(mContext)
//                        .setShowMessage(false)
//                        .setCancelable(false)
//                        .setCancelOutside(false)
//                        .create();
//        mLoadingDialog.show();
        ((BaseActivity)mContext).showLoading();
    }

    public void showLoading(String msg){
//        mLoadingDialog =
//                new LoadingDialog.Builder(mContext)
//                        .setShowMessage(true)
//                        .setMessage(msg)
//                        .setCancelable(false)
//                        .setCancelOutside(false)
//                        .create();
//        mLoadingDialog.show();
        ((BaseActivity)mContext).showLoading(msg);
    }

    public void hideLoading(){
/*        if (mLoadingDialog!=null) {
            mLoadingDialog.dismiss();
        }*/
        ((BaseActivity)mContext).hideLoading();
    }

    /**
     * 判断activity与fragment的连接情况
     * @return
     */
    public boolean isAttachedContext(){
        return getActivity() != null;
    }

    public void checkActivityAttached(){
        if (null == getActivity()) {
            throw new ActivityNotAttachedException();
        }
    }

    public void showToast(String msg){
        ((BaseActivity)mContext).showToast(msg);
    }

    public void showError(String error){
        ((BaseActivity)mContext).showError(error);
    }

    protected abstract void getBundleExtras(Bundle bundle);

    // 初始化UI setContentView
    protected abstract View initContentView(
            LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState);

    /**
     * fragment加载数据时调用，此时控件已初始化完毕
     */
    protected abstract void initLogic();

    public static class ActivityNotAttachedException extends RuntimeException{
        public ActivityNotAttachedException(){
            super("Fragment has disconnected from Activity ! - -.");
        }
    }
}
